<template>
  <t-link
    theme="primary"
    @click="handleOpenDialog('read', { id:props.id, fileUrlList: [] })"
  >
    查看
  </t-link>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData }"
    :api-map="{ get: interactionListCRUD.get }"
    header="查看"
    width="80%"
    @request-success="handleDialogRequestSuccess"
    @refresh="hanldeClose"
    placement="top"
    top="50px"
  >
  <!-- 订单信息：客户姓名 楼盘名称 地址 -->
    <div><span style="font-size: 16px; margin-right: 2px;">{{ formData.name }}</span>{{ propertyInfoList.find((item) => item.id === formData.propertyName)?.name }}  <span></span> <span>{{ formData.address }}</span>	</div>
     <!-- 话题内容 -->
    <div style="font-weight: bold;">{{ formData.content }}</div>
    <!-- 发起人 发起时间 -->
    <t-comment
      :datetime="dayjs(formData.createTime).format('YYYY-MM-DD HH:mm:ss')"
    >    
      <template #author>
         <span style="font-size:14px;font-weight:normal;">发起人：</span> {{userStore.getUserNameById(formData.creator)}}
      </template>
    </t-comment>


    <!-- 接收人 新增接收人 -->
    <div style="display: flex;justify-content: space-between;">
      <div >接收人：{{(JSON.parse(formData.senders).map((id: any)=>userStore.getUserNameById(id))).join('、')}}</div>
      <add-reciver :id="props.id" :readonly="props.readonly" :senders="JSON.parse(formData.senders)" @request-success="handleRequestSuccess"/>
    </div>
    
   
    
    <!-- 图片/文件 -->
    <div class="file-container">
      <template v-for="(file2, index) in JSON.parse(formData.fileUrl)" :key="index">
        <file-preview :file="file2" />
      </template>
    </div>
    <t-divider></t-divider>
    <t-list :split="true" style="height: 320px;">
    <t-list-item v-for="(item, index) in interactionComments" :key="index">
      <template #content>
        <t-comment  
          :author="userStore.getUserNameById(item.creator)" 
          >
          <template #datetime>
            {{dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')}}
            <span style="color: #333;">已读：{{(JSON.parse(item.readUserIds).map((id: any)=>userStore.getUserNameById(id))).join('、')}}</span>
          </template>
          <template #content>
            {{item.content}}
            <div v-if="item.fileUrl"  class="file-container">
              <template v-for="(file2, index) in JSON.parse(item.fileUrl)" :key="index">
                <file-preview :file="file2" />
              </template>
            </div>
          </template>
          <template #actions>
            <t-space key="chat" :size="6" @click="handleReplayChild(item.id)">
              <t-icon name="chat" />
              <span >回复</span>
            </t-space>
          </template>
          <template #reply>
            <t-list :split="true" v-if="item.children">
              <t-list-item v-for="(comment, index) in item.children" :key="index">
                <template #content>
                  <t-comment
                  >
                    <template #author>
                      <span>{{ userStore.getUserNameById(comment.creator) }}</span>
                      <t-icon name="caret-right-small" size="medium" style="margin: 0 4px" />
                      <span>{{ userStore.getUserNameById(item.creator) }}</span>
                    </template>
                    <template #datetime>
                      {{dayjs(comment.createTime).format('YYYY-MM-DD HH:mm:ss')}}
                      <span style="color: #333;">已读：{{(JSON.parse(comment.readUserIds).map((id: any)=>userStore.getUserNameById(id))).join('、')}}</span>
                    </template>
                    <template #content>
                      {{comment.content}}
                      <div v-if="comment.fileUrl"  class="file-container">
                        <template v-for="(file, index) in JSON.parse(comment.fileUrl)" :key="index">
                          <file-preview :file="file" />
                        </template>
                      </div>
                    </template>

        
                  </t-comment>
                </template>
              </t-list-item>
             </t-list>
          </template>
        </t-comment>
      </template>
    </t-list-item>
  </t-list>
  <t-comment>
    <template #content>
      <div class="form-container">
        <upload 
            multiple
            v-model:files="formData.fileUrlList" 
            :disabled="props.readonly"
          >
          <template #trigger>
            <t-link theme="primary">
              <template #prefix-icon>
                <link-icon size="large" style="font-size: 20px;"/>
              </template>
            </t-link>
          </template>
        </upload>
        <mention
          v-model:value="formData.comments"
          v-model:selected-keys="formData.atUserIds"
          placeholder="可输入@成员"
          :options="orderRelevantPerson"
        />  
        <div class="form-submit">
          <t-button  @click="handleReply" :disabled="props.readonly">回复</t-button>
        </div>
      </div>
    </template>
  </t-comment>
   
  </custom-dialog>
  <t-dialog v-model:visible="visible" attach="body" header="回复留言" >
    <div class="form-container">
        <upload 
            multiple
            v-model:files="reply.fileUrl" 
          >
          <template #trigger>
            <t-link theme="primary">
              <template #prefix-icon>
                <link-icon />
              </template>
            </t-link>
          </template>
        </upload>
        <mention
        v-model:value="reply.content"
        v-model:selected-keys="reply.atUserIds"
        placeholder="可输入@成员"
        :options="orderRelevantPerson"
      />
        <!-- <t-button class="form-submit" @click="handleReply">回复</t-button> -->
      </div>
      <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button  @click="handleReplayContent">回复</t-button>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { LinkIcon, JumpIcon } from 'tdesign-icons-vue-next';
import { computed, nextTick, reactive, ref, useTemplateRef } from 'vue';
import dayjs from 'dayjs';
import { getOrderRelevantPerson } from '@/api/order/basic';
import { interactionListCRUD,interactionCommentsCRUD} from '@/api/notice/interaction';
import CustomDialog from '@/components/custom/dialog/index.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import Mention from '@/components/mention/index.vue';
import FilePreview from '@/components/file-preview/index.vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { getSimpleUserList } from '@/api/system/user';
import { propertyManageCRUD } from '@/api/config/property';
import AddReciver from './AddReciver.vue';
import Upload from '@/components/upload/index.vue';
import listToTree from '@/utils/listToTree';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// props
const props = defineProps({
  id: {
    type: Number,
    required: true
  },
  readonly: {
    type:Boolean,
    default:false
  }
});
// emits
const emits = defineEmits(['requestSuccess']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {

  handleGetComments()
  customDialogRef.value.open(mode, params);
  nextTick(() => {
    handleGetOrderRelevantPerson();
  });

};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
const hanldeClose = () => {
  if(!props.readonly) {
    emits('requestSuccess',{mode:'update'});
  }
}
// 获取所有人
const allUsers = ref([]);
const handleGetAllUser = () => {
  getSimpleUserList()
    .then((data) => {
      allUsers.value = data
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetAllUser()
// 订单相关人员
// const orderRelevantPerson = ref([]);
// 处理获取订单相关人员
const handleGetOrderRelevantPerson=() => {
   if(customDialogRef.value.formData.senders) {
    // orderRelevantPerson.value = allUsers.value.filter(item => JSON.parse(customDialogRef.value.formData.senders).includes(item.id));
   }
}
const orderRelevantPerson = computed(() => {
  if (!customDialogRef.value?.formData?.senders || allUsers.value.length === 0) {
    return [];
  }
  try {
    const senders = JSON.parse(customDialogRef.value.formData.senders);
    return allUsers.value.filter(item => senders.includes(item.id));
  } catch (e) {
    return [];
  }
});
const interactionComments = ref([])
const handleGetComments = () => {
  const params = {
    pageSize: -1,
    interactionId:props.id
  }
  interactionCommentsCRUD.page(params).then((data) => {
    interactionComments.value = listToTree(data.list);
    console.log(interactionComments.value,'kk');
    
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 回复
const handleReply = () => {
  if(!customDialogRef.value.formData.comments) {
    MessagePlugin.warning('请输入回复内容');
    return
  }
  const params = {
    interactionId:props.id,
    content:customDialogRef.value.formData.comments,
    atUserIds:customDialogRef.value.formData.atUserIds,
    fileUrl:customDialogRef.value.formData.fileUrlList
  }
  interactionCommentsCRUD.create(params).then((data) => {
    handleGetComments()
    customDialogRef.value.formData.comments=''
    customDialogRef.value.formData.atUserIds=[]
    customDialogRef.value.formData.fileUrlList=[]
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 子回复弹框
const handleReplayChild = (id:any) => {
  reply.parentId = id
  visible.value = true
}
const visible = ref(false)
const reply = reactive({
  content:'',
  atUserIds:[],
  fileUrl:[],
  parentId:'',
  interactionId:props.id
})
// 回复
const handleReplayContent = () => {
  if(!reply.content) {
    MessagePlugin.warning('请输入回复内容');
    return
  }
  interactionCommentsCRUD.create(reply).then((data) => {
    handleGetComments()
    visible.value =false
    reply.content = ''
    reply.atUserIds = []
    reply.fileUrl = []
  })
  .catch(({ message }) => {
    MessagePlugin.error(message);
  });
}
// 处理请求成功
const handleRequestSuccess = () => {
  // 重新获取对话框数据
  if (customDialogRef.value) {
    const params = { id: props.id };
    handleOpenDialog('read', params)
  }
};


</script>
<style lang="less" scoped>
.form-container {
  margin-top: 6px;
  display: flex;
  flex-direction: column;
  // align-items: flex-end;
  .form-submit {
    margin-top: 8px;
    display: flex;
    justify-content: flex-end;
  }
}

.file-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin: 12px 0;
}
:deep(.t-comment__reply) {
  padding: 0;
}
</style>
